package com.jiuyou.storeController.vipPayment;

import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.core.util.AdapaySign;
import com.huifu.adapay.model.Payment;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.adapayRecordB.domain.AdapayRecordB;
import com.ruoyi.adapayRecordB.service.IAdapayRecordBService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.paymentConfig.domain.PaymentConfig;
import com.ruoyi.paymentConfig.service.IPaymentConfigService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.store.service.IStoreService;
import com.ruoyi.storeUser.service.IStoreUserService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/store/vipPayment")
public class VipPaymentStoreController extends StoreBaseController {
    private static final Logger log = LoggerFactory.getLogger(VipPaymentStoreController.class);
    @Autowired
    private IPaymentConfigService paymentConfigService;
    @Autowired
    private IAdapayRecordBService adapayRecordBService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IStoreUserService storeUserService;
    @Autowired
    private IStoreService storeService;
    //付款，
    /**
     * 需要支付的订单id
     * @param payId
     * @return
     */
    @PostMapping("/pay")
    public AjaxResult pay( Long payId)  {
        PaymentConfig paymentConfig= paymentConfigService.selectPaymentConfigById(payId);
        if(null==paymentConfig){
            return AjaxResult.unAuthorize();
        }
       if(!DicConstants.SYS_Y.getCode().equals(paymentConfig.getState())) {
           return AjaxResult.error("该选项不可用，请重新进入后再试");
       }

        Long loginStoreUserId =getLoginStoreUserId();
        if(null==loginStoreUserId) {
            return AjaxResult.unLogin();
        }
        StoreUserRole storeUserRole=getStoreUserRole();
        Long storeId= storeUserRole.getStoreId();
        Store store=storeService.selectStoreById(storeId);
        if(null==store) {
            return AjaxResult.unAuthorize();
        }
        StoreUser storeUser=storeUserService.selectStoreUserById(loginStoreUserId);
        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        System.out.println("=======execute payment begin=======");
        Map<String, Object> paymentParams = new HashMap<>(10);
        String app_id=configService.selectConfigByKey("adpay_app_id_B");
        paymentParams.put("app_id", app_id);
        String order_no="wx" + System.currentTimeMillis();
        paymentParams.put("order_no", order_no);
        paymentParams.put("pay_channel", "wx_lite");
        BigDecimal payPrice=paymentConfig.getPrice().setScale(2, RoundingMode.HALF_UP);
        if(payPrice.compareTo(new BigDecimal("0"))==0){
            return AjaxResult.error("0元订单无法支付");
        }
        String payname=paymentConfig.getName();
        Integer days=paymentConfig.getDays();
        String pay_amt=payPrice.toString();
        paymentParams.put("pay_amt", pay_amt);

        paymentParams.put("goods_title",payname);
        paymentParams.put("goods_desc", payname);

        paymentParams.put("div_members", "");
//        paymentParams.put("pay_mode", "delay");
        Map<String, Object> expendParams = new HashMap<>(2);
        String openId = storeUser.getOpenId();//微信授权获取
        expendParams.put("open_id", openId);
        paymentParams.put("expend", expendParams);
        String domain=configService.selectConfigByKey("domain");
        String notify_url=/*request.getScheme()+*/domain+"/prod-api/store/vipPayment/notify";
        paymentParams.put("notify_url", notify_url);

        AdapayRecordB adapayRecordb=new AdapayRecordB();
        adapayRecordb.setPayOrderId(order_no);
        adapayRecordb.setStoreId(storeId);
        adapayRecordb.setStoreName(store.getStoreName());
        adapayRecordb.setReqState(DicConstants.SYS_Y.getCode());
        adapayRecordb.setReqParam(paymentParams.toString());
        adapayRecordb.setCreateBy(storeUser.getId());
        adapayRecordb.setPayMoney(payPrice);
        adapayRecordb.setPayName(payname);
        adapayRecordb.setPayDays(days);
        try {

            payment = Payment.create(paymentParams);
        } catch (BaseAdaPayException e) {
            e.printStackTrace();
            adapayRecordb.setReqState((DicConstants.SYS_N.getCode()));
            adapayRecordb.setReqFailMsg(e.getMessage());
            adapayRecordBService.insertAdapayRecordB(adapayRecordb);
            return AjaxResult.error(e.getMessage());
        }
        adapayRecordb.setResParam(payment.toString());
        String error_code = (String) payment.get("error_code");
        if (null != error_code) {

            String error_msg = (String) payment.get("error_msg");
            System.out.println("error_code:" + error_code + "............." + error_msg);
            adapayRecordb.setReqState((DicConstants.SYS_N.getCode()));
            adapayRecordb.setReqFailMsg(error_msg);
            adapayRecordBService.insertAdapayRecordB(adapayRecordb);
            return AjaxResult.error(error_msg);
        }

        adapayRecordb.setPaymentId( (String)payment.get("id"));
        adapayRecordBService.insertAdapayRecordB(adapayRecordb);
        return  AjaxResult.success(payment);
    }

    //回调
    /**
     * 支付付款回调
     * @param request
     */
    @RequestMapping("/notify")
    public void notify(HttpServletRequest request) {
        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");
            //验签标记
            boolean checkSign;
            //验签请参publicKey
            String publicKey = AdapayCore.PUBLIC_KEY;
            log.info("验签请参：data={}sign={}");
            //验签
            checkSign = AdapaySign.verifySign(data, sign, publicKey);
            if(checkSign){
                //验签成功逻辑
                System.out.println("成功返回数据data:"+data);
                JSONObject dataJson= JSONObject.parseObject(data);
                // pending 交易处理中 succeeded 交易成功 failed失败

                String order_no=dataJson.getString("order_no");//交易订单号？wx开头加时间戳
                AdapayRecordB adapayRecordBQuery=new AdapayRecordB();
                adapayRecordBQuery.setPayOrderId(order_no);
                List<AdapayRecordB>  list=adapayRecordBService.selectAdapayRecordBList(adapayRecordBQuery);
                if(list.size()>0){
                    AdapayRecordB adapayRecordB=list.get(0);
                    String payState=adapayRecordB.getPayState();
                    if("succeeded".equals(payState)){
                        //已经处理过
                        return;
                    }
                    AdapayRecordB adapayRecordBUpdate=new AdapayRecordB();
                    adapayRecordBUpdate.setId(adapayRecordB.getId());
                    adapayRecordBUpdate.setNotifyParam(data);
                    String status=dataJson.getString("status");
                    String error_msg=dataJson.getString("error_msg");
                    adapayRecordBUpdate.setPayState(status);
                    if("succeeded".equals(status)){
                        //交易成功,更新時間
                        storeUpdataVipTime(adapayRecordB);
                    }
                    if("failed".equals(status)){
                        //交易失败
                        adapayRecordBUpdate.setPayFailMsg(error_msg);
                    }
                    adapayRecordBUpdate.setUpdateTime(new Date());
                    adapayRecordBService.updateAdapayRecordB(adapayRecordBUpdate);
                }

            }else {
                //验签失败逻辑
            }
        }catch (Exception e){
            log.info("异步回调开始，参数，request={}");
        }
        return ;
    }

    /**
     * 測試方法
     */
    @RequestMapping("/test")
    public void test(Long id) {
        AdapayRecordB adapayRecordB=   adapayRecordBService.selectAdapayRecordBById(id);
        storeUpdataVipTime(adapayRecordB);
    }


    private void storeUpdataVipTime(AdapayRecordB adapayRecordB){
       Long storeId= adapayRecordB.getStoreId();
        Store store= storeService.selectStoreById(storeId);
        Date vipTime= store.getVipTime();
        if(vipTime==null){
            vipTime=new Date();
        }
        if(vipTime.compareTo(new Date())>0){
            //之前就是vip在原来的基础上加时间
        }else{
            //现在开始算时间
            vipTime=new Date();
        }
        Date newVipDate= DateUtils.addDays(vipTime,adapayRecordB.getPayDays());
        Store storeUpdate=new Store();
        storeUpdate.setId(store.getId());
        storeUpdate.setVipState(DicConstants.SYS_Y.getCode());
        storeUpdate.setVipTime(newVipDate);
        storeService.updateStore(storeUpdate);
    }


    //支付记录
    @ApiOperation(value = "支付记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前第几页",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize",value = "每页几条数据",required = true,dataType = "Integer"),
    })
    @PostMapping("/listAdapayRecordB")
    public AjaxResult listAdapayRecordB(Integer pageNum, Integer pageSize)
    {
//        Long loginStoreUserId =getLoginStoreUserId();
//        if(null==loginStoreUserId){
//            return AjaxResult.unLogin();
//        }
        StoreUserRole storeUserRole = getStoreUserRole();
        startPage();
        AdapayRecordB adapayRecordB=new AdapayRecordB();
//        adapayRecordB.setCreateBy(loginStoreUserId);
        adapayRecordB.setStoreId(storeUserRole.getStoreId());
        List<AdapayRecordB> list=adapayRecordBService.selectAdapayRecordBList(adapayRecordB);
        for (AdapayRecordB adp:list) {
            if(StringUtils.isEmpty(adp.getPayState())){
                adp.setPayState(DicConstants.HUIFU_PAYSTATE_INIT.getName());
            }else if(adp.getPayState().equals(DicConstants.HUIFU_PAYSTATE_INIT.getCode())){
                adp.setPayState(DicConstants.HUIFU_PAYSTATE_INIT.getName());
            }else if(adp.getPayState().equals(DicConstants.HUIFU_PAYSTATE_SUCCESS.getCode())){
                adp.setPayState(DicConstants.HUIFU_PAYSTATE_SUCCESS.getName());
            }else if(adp.getPayState().equals(DicConstants.HUIFU_PAYSTATE_FAILED.getCode())){
                adp.setPayState(DicConstants.HUIFU_PAYSTATE_FAILED.getName());
            }
        }

        TableDataInfo tableDataInfo=getDataTable(list);
        return AjaxResult.success(tableDataInfo);
    }

    //支付选项记录
    @ApiOperation(value = "付费方式列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "当前第几页",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize",value = "每页几条数据",required = true,dataType = "Integer"),
    })
    @PostMapping("/listPaymentConfig")
    public AjaxResult listPaymentConfig(Integer pageNum, Integer pageSize)
    {
        Long loginStoreUserId =getLoginStoreUserId();
        if(null==loginStoreUserId){
            return AjaxResult.unLogin();
        }
        PaymentConfig paymentConfigParam=new PaymentConfig();
        paymentConfigParam.setState(DicConstants.SYS_Y.getCode());
        startPage();
        List<PaymentConfig> list=paymentConfigService.selectPaymentConfigList(paymentConfigParam);
        TableDataInfo tableDataInfo=getDataTable(list);
        return AjaxResult.success(tableDataInfo);
    }


}
